// import pako from 'pako'

const token = uni.getStorageSync("blueDemoness-refreshToken");
class socket {
  //  constructor(url =  `wss://ai.bithinex.xyz/infra/ws?token=${token}`, options) {
   // constructor(url =  `ws://192.168.1.6:48082/infra/ws?token=${token}`, options) {
	// constructor(url =  `wss://zvsvs.com/infra/ws?token=${token}`, options) {
		constructor(url =  `wss://blue.trading-code.com/infra/ws?token=${token}`, options) {
  // constructor(url = `wss://100x.lhxjq.com/infra/ws?token=${token}`, options) {
    this.heartBeatTimer = null;
    this.options = options;
    this.messageMap = {};
    this.connState = 0;
    this.socket = null;
    this.url = url;
  }
  doOpen() {
    if (this.connState) return;
    this.connState = 1;
    this.afterOpenEmit = [];
    const BrowserWebSocket = window.WebSocket || window.MozWebSocket;
    const socket = new BrowserWebSocket(this.url);
    socket.binaryType = "arraybuffer";
    socket.onopen = (evt) => this.onOpen(evt);
    socket.onclose = (evt) => this.onClose(evt);
    socket.onmessage = (evt) => this.onMessage(evt.data);
    socket.onerror = (err) => this.onError(err);
    this.socket = socket;
  }
  onOpen(evt) {
    this.connState = 2;
    //this.heartBeatTimer = setInterval(this.checkHeartbeat.bind(this), 20000)
    this.onReceiver({ Event: "open" });
    console.log("连接成功");
  }
  checkOpen() {
    return this.connState === 2;
  }
  onClose() {
    this.connState = 0;
    if (this.connState) {
      this.onReceiver({ Event: "close" });
    }
    console.log("连接关闭");
  }
  send(data) {
    this.socket.send(JSON.stringify(data));
  }
  onMessage(message) {
    try {
      let strMessage;

      // 如果是字符串，直接使用
      if (typeof message === "string") {
        strMessage = message;
      }
      // 如果是 ArrayBuffer，尝试解压
      // else if (message instanceof ArrayBuffer) {
      //   // 使用 pako 解压 GZIP 数据
      //   const dataArray = new Uint8Array(message);
      //   const decompressedData = pako.inflate(dataArray, { to: 'string' });
      //   strMessage = decompressedData;
      // }
      else {
        throw new Error("Unsupported message type");
      }

      // 解析 JSON
      const data = JSON.parse(strMessage);
      this.onReceiver({ Event: "message", Data: data });
      // 处理消息
      /*
      if (data.ping) {
        this.send({ pong: data.ping });
      } else if (data.ch) {
        //console.log(' >> onMessage:',  data.tick);
        this.onReceiver({ Event: "message", Data: data });
      } else if (data.op === 'pong') {
        this.onReceiver({ Event: 'pong', Data: data });
      }
        */
    } catch (err) {
      console.error(" >> Data parsing error:", err);
    }
  }
  checkHeartbeat() {
    const data = {
      cmd: "ping",
      args: [Date.parse(new Date())],
    };
    this.send(data);
  }
  onError(err) {}
  onReceiver(data) {
    const callback = this.messageMap[data.Event];
    if (callback) callback(data.Data);
  }
  on(name, handler) {
    this.messageMap[name] = handler;
  }
  doClose() {
    this.socket.close();
  }
  destroy() {
    if (this.heartBeatTimer) {
      clearInterval(this.heartBeatTimer);
      this.heartBeatTimer = null;
    }
    this.doClose();
    this.messageMap = {};
    this.connState = 0;
    this.socket = null;
  }
}

export default socket;
